"use strict"

const Controller = require("egg").Controller
const BaseController = require("./base")
class CategoryController extends BaseController {
  async Success(result, msg) {
    const { ctx } = this
    ctx.body = {
      code: 200,
      data: {
        code: 200,
        msg: msg,
        data: result,
      },
    }
  }
  async Error(msg) {
    const { ctx } = this
    ctx.body = {
      code: 5000,
      data: {
        code: 5000,
        msg,
      },
    }
  }
  //获取所有图书分类信息
  async index() {
    const { ctx, service } = this
    const { pageNum, pageSize, ...where } = ctx.query
    const result = await service.category.list(
      isNaN(pageNum) ? 1 : parseInt(pageNum),
      isNaN(pageSize) ? 3 : parseInt(pageSize),
      where
    )
    if (result) {
      //console.log(result.data);
      this.Success(result, "获取成功")
    } else {
      this.Error("获取失败")
    }
  }
  //获取单条图书分类信息
  async single() {
    const { ctx, service } = this
    const categoryId = ctx.params.id
    const result = await service.category.single(categoryId)
    if (result) {
      this.Success(result, "获取成功")
    } else {
      this.Error("获取失败")
    }
  }
  //创建图书分类
  async create() {
    const { ctx, service } = this
    const category = ctx.request.body
    const isExists = await service.category.isExist(category.category_name)
    if (isExists.length > 0) {
      this.Error("该分类已存在")
    } else {
      const result = await service.category.create(category)
      if (result.affectedRows === 1) {
        this.Success(result, "新增成功")
      } else {
        this.Error("新增失败")
      }
    }
  }
  //修改图书分类
  async update() {
    const { ctx, service } = this
    const id = ctx.params.id
    const category = ctx.request.body
    category.id = id
    const result = await service.category.update(category)
    if (result.affectedRows === 1) {
      this.Success(result, "修改成功")
    } else {
      this.Error("修改失败")
    }
  }

  //删除图书分类
  async destroy() {
    const { ctx, service } = this
    const id = ctx.params.id
    const result = await service.category.destroy(id)
    if (result.affectedRows === 1) {
      this.Success(result, "删除成功")
    } else {
      this.Error("删除失败")
    }
  }
  //获取单条图书分类下的所有书籍
  async getCateGorySingleInfoAll() {
    const { ctx, service } = this
    const categoryId = ctx.params.id
    const result = await service.category.getCateGorySingleInfoAll(categoryId)
    if (result) {
      this.Success(result, "获取成功")
    } else {
      this.Error("获取失败")
    }
  }
 
}
module.exports = CategoryController
